from django import forms
from django.core.validators import ValidationError
from django.shortcuts import render, redirect
from django.urls import re_path, reverse
from django.utils.safestring import mark_safe

from stark.service.v1 import StarkHandler, StarkForm, StarkModelForm, Option, get_boolean_text, get_m2m_text
from web import models
from web.utils import md5
from .base import PermissionHandler


class UserInfoAddModelForm(StarkModelForm):
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput)
    exclude_bootstrap_class = ['is_depart']
    class Meta:
        model = models.UserInfo
        fields = ['username', 'password', 'confirm_password', 'nickname', 'depart', 'is_depart']
        widgets = {
            'password': forms.PasswordInput,
            'confirm_password': forms.PasswordInput,
        }

    def clean_confirm_password(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if password != confirm_password:
            raise ValidationError('两次输入密码不一致,请重新输入！')
        return confirm_password

    def clean(self):
        password = self.cleaned_data['password']
        self.cleaned_data['password'] = md5.gen_md5(password)
        return self.cleaned_data


class UserInfoChangeModelForm(StarkModelForm):
    class Meta:
        model = models.UserInfo
        fields = ['username', 'nickname', 'depart', 'is_depart', 'roles']


class ResetPasswordForm(StarkForm):
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput)

    def clean_confirm_password(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if len(confirm_password) < 6:
            raise ValidationError('密码长度不得小于6位')
        if password != confirm_password:
            raise ValidationError('两次密码输入不一致，请重新输入')
        return confirm_password

    # def clean(self):
    #     password = self.cleaned_data['password']
    #     self.cleaned_data['password'] = md5.gen_md5(password)
    #     return self.cleaned_data


class CurrentUserInfoChangeForm(StarkForm):
    nickname = forms.CharField(label='姓名', required=True)
    password = forms.CharField(label='密码', widget=forms.PasswordInput, required=True)
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput, required=True)

    def clean_confirm_password(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if len(confirm_password) < 6:
            raise ValidationError('密码长度不得小于6位')
        if password != confirm_password:
            raise ValidationError('两次密码输入不一致，请重新输入')
        return confirm_password

    # def clean(self):
    #     password = self.cleaned_data['password']
    #     self.cleaned_data['password'] = md5.gen_md5(password)
    #     return self.cleaned_data


class UserInfoHandler(PermissionHandler, StarkHandler):
    def display_reset_pwd(self, obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return '重置密码'
        return mark_safe('<a href="%s">重置密码</a>' % self.reverse_commons_url(self.get_reset_pwd_url_name, pk=obj.id))

    list_display = ['nickname',
                    'depart', get_m2m_text('角色', 'roles'),
                    get_boolean_text('部门是否生效', 'is_depart'),
                    display_reset_pwd,
                    ]

    def get_model_class_form(self, is_add, request, pk, *args, **kwargs):
        if is_add:
            return UserInfoAddModelForm
        return UserInfoChangeModelForm

    def reset_password(self, request, pk):
        current_object = self.model_class.objects.filter(id=pk).first()
        if not current_object:
            info = '数据不存在，请重新选择!'
            return render(request, 'stark/hint.html', {'msg': info})
        if request.method == "GET":
            form = ResetPasswordForm()
            return render(request, 'stark/change.html', {'form': form})
        form = ResetPasswordForm(data=request.POST)
        if form.is_valid():
            password = form.cleaned_data['password']
            current_object.password = md5.gen_md5(password)
            current_object.save()
            return redirect(self.reverse_list_url())
        return render(request, 'stark/change.html', {'form': form})

    @property
    def get_reset_pwd_url_name(self):
        return self.get_url_name('reset_pwd')

    def extra_url(self):
        patterns = [
            re_path(r'^reset/password/(?P<pk>\d+)/$', self.wrapper(self.reset_password),
                    name=self.get_reset_pwd_url_name),
        ]
        return patterns

    search_list = ['nickname__contains', 'username__contains']
    search_group = [
        Option(field='depart'),
    ]


def current_userinfo_change(request):
    current_user_id = request.session['user_info']['user_id']
    current_object = models.UserInfo.objects.filter(id=current_user_id).first()
    pwd = current_object.password
    if pwd == md5.gen_md5('123456'):
        msg = '请修改初始密码'
    else:
        msg = '个人信息修改'
    if request.method == 'GET':
        form = CurrentUserInfoChangeForm(initial={'nickname': current_object.nickname})
        return render(request, 'web/change.html', {'form': form, 'msg': msg})
    form = CurrentUserInfoChangeForm(data=request.POST)

    if form.is_valid():
        password = form.cleaned_data['password']
        nickname = form.cleaned_data['nickname']
        current_object.nickname = nickname
        current_object.password = md5.gen_md5(password)
        current_object.save()
        return redirect(reverse('index'))
    return render(request, 'web/change.html', {'form': form, 'msg': msg})
